﻿using PuppeteerSharp;
using PuppeteerSharp.Media;
using System;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Mail;
using System.Threading.Tasks;

namespace DzInfo.Tools.Web
{
    public class ScreenCaptureService
    {
        private readonly string _chromiumPath;
        private const string DefaultChromiumDir = "Chromium";

        public ScreenCaptureService(string chromiumPath = null)
        {
            _chromiumPath = chromiumPath;
        }

        public void CaptureAndSend(string url, string recipientEmail)
        {
            CaptureAndSendAsync(url, recipientEmail).GetAwaiter().GetResult();
        }

        private async Task CaptureAndSendAsync(string url, string recipientEmail)
        {
            string tempDir = Path.Combine(Path.GetTempPath(), "K3Capture");
            Directory.CreateDirectory(tempDir);

            string imagePath = Path.Combine(tempDir, "dashboard.png");
            string pdfPath = Path.Combine(tempDir, "dashboard.pdf");

            IBrowser browser = null;
            try
            {
                // 初始化浏览器
                browser = await LaunchBrowserAsync();

                using (var page = await browser.NewPageAsync())
                {
                    // 导航到目标URL
                    await page.GoToAsync(url, new NavigationOptions
                    {
                        WaitUntil = new[] { WaitUntilNavigation.Networkidle0 },
                        Timeout = 60000
                    });

                    // 设置视口大小（1920x1080）
                    await page.SetViewportAsync(new ViewPortOptions
                    {
                        Width = 1920,
                        Height = 1080,
                        DeviceScaleFactor = 2 // 高清截图
                    });

                    // 等待额外时间确保大屏渲染完成
                    await Task.Delay(5000);

                    // 截图选项 - 适配19.0.2版本API
                    var screenshotOptions = new ScreenshotOptions
                    {
                        FullPage = true,
                        Quality = 100,
                        Type = ScreenshotType.Png,
                        OmitBackground = true
                    };

                    // 截图 - 适配19.0.2版本API
                    var screenshotData = await page.ScreenshotDataAsync(screenshotOptions);
                    File.WriteAllBytes(imagePath, screenshotData);

                    // PDF选项 - 适配19.0.2版本API
                    var pdfOptions = new PdfOptions
                    {
                        Format = PaperFormat.A2,
                        Landscape = true,
                        PrintBackground = true,
                        MarginOptions = new MarginOptions
                        {
                            Top = "0px",
                            Right = "0px",
                            Bottom = "0px",
                            Left = "0px"
                        }
                    };

                    // 生成PDF - 适配19.0.2版本API
                    var pdfData = await page.PdfDataAsync(pdfOptions);
                    File.WriteAllBytes(pdfPath, pdfData);
                }

                // 发送邮件
                SendEmail(recipientEmail, imagePath, pdfPath);
            }
            catch (Exception ex)
            {
                LogError($"操作失败: {ex}");
                throw;
            }
            finally
            {
                // 确保浏览器关闭
                if (browser != null)
                {
                    await browser.CloseAsync();
                }

                // 清理临时文件
                CleanupFiles(imagePath, pdfPath);
            }
        }

        private async Task<IBrowser> LaunchBrowserAsync()
        {
            // 优先使用预提供的Chromium路径
            if (!string.IsNullOrEmpty(_chromiumPath) && File.Exists(_chromiumPath))
            {
                return await Puppeteer.LaunchAsync(new LaunchOptions
                {
                    Headless = true,
                    ExecutablePath = _chromiumPath,
                    Args = new[] { "--no-sandbox", "--disable-setuid-sandbox" }
                });
            }

            // 检查默认Chromium目录
            string defaultExecutable = FindChromiumExecutable();
            if (!string.IsNullOrEmpty(defaultExecutable))
            {
                return await Puppeteer.LaunchAsync(new LaunchOptions
                {
                    Headless = true,
                    ExecutablePath = defaultExecutable,
                    Args = new[] { "--no-sandbox", "--disable-setuid-sandbox" }
                });
            }

            // 让PuppeteerSharp自动处理浏览器下载
            try
            {
                // 设置浏览器下载路径
                string downloadPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, DefaultChromiumDir);

                // 创建浏览器下载器但不直接使用它
                var browserFetcher = new BrowserFetcher(new BrowserFetcherOptions
                {
                    Path = downloadPath
                });

                // 不需要手动调用下载，Puppeteer.LaunchAsync会自动处理
                return await Puppeteer.LaunchAsync(new LaunchOptions
                {
                    Headless = true,
                    Args = new[] { "--no-sandbox", "--disable-setuid-sandbox" }
                });
            }
            catch (Exception ex)
            {
                // 尝试直接启动浏览器（可能已经下载）
                try
                {
                    return await Puppeteer.LaunchAsync(new LaunchOptions
                    {
                        Headless = true,
                        Args = new[] { "--no-sandbox", "--disable-setuid-sandbox" }
                    });
                }
                catch
                {
                    throw new Exception("无法初始化Chromium浏览器: " + ex.Message);
                }
            }
        }

        private string FindChromiumExecutable()
        {
            // 在应用目录查找Chromium
            string appDir = AppDomain.CurrentDomain.BaseDirectory;
            string chromiumDir = Path.Combine(appDir, DefaultChromiumDir);

            if (Directory.Exists(chromiumDir))
            {
                // 查找Windows可执行文件
                string winExe = Path.Combine(chromiumDir, "Win64-884014", "chrome-win", "chrome.exe");
                if (File.Exists(winExe)) return winExe;

                // 查找Linux可执行文件
                string linuxExe = Path.Combine(chromiumDir, "Linux-884014", "chrome-linux", "chrome");
                if (File.Exists(linuxExe)) return linuxExe;

                // 备用查找：递归搜索chrome.exe
                var files = Directory.GetFiles(chromiumDir, "chrome.exe", SearchOption.AllDirectories);
                if (files.Length > 0) return files[0];
            }

            return null;
        }

        private void SendEmail(string to, params string[] attachments)
        {
            using (var client = new SmtpClient("smtp.qiye.aliyun.com", 25))
            {
                client.Credentials = new NetworkCredential("it@dna-group.com", "Dna111222");
                client.EnableSsl = true;
                client.Timeout = 30000;

                using (var message = new MailMessage("it@dna-group.com", to))
                {
                    message.Subject = $"企业大屏快照 {DateTime.Now:yyyy-MM-dd HH:mm}";
                    message.Body = "附件包含当前大屏截图及PDF文档";
                    message.IsBodyHtml = false;

                    foreach (var file in attachments)
                    {
                        if (File.Exists(file))
                        {
                            message.Attachments.Add(new Attachment(file));
                        }
                    }

                    client.Send(message);
                }
            }
        }

        private void CleanupFiles(params string[] files)
        {
            foreach (var file in files)
            {
                try
                {
                    if (File.Exists(file))
                    {
                        File.Delete(file);
                    }
                }
                catch (Exception ex)
                {
                    LogError($"文件清理失败: {file} - {ex.Message}");
                }
            }
        }

        private void LogError(string message)
        {
            try
            {
                string logPath = Path.Combine(Path.GetTempPath(), "K3Capture_errors.log");
                File.AppendAllText(logPath, $"[{DateTime.Now:yyyy-MM-dd HH:mm:ss}] {message}\n");
            }
            catch
            {
                // 忽略日志错误
            }
        }
    }
}